package logic

import (
	"common/model"
	"context"
	product "product_server/proto"
)

func (p *ProductServer) BargainProductList(ctx context.Context, req *product.BargainProductListRequest) (*product.BargainProductListResponse, error) {
	page := req.Pages
	if page <= 0 {
		page = 1
	}
	pageSize := req.PagePerNums
	if pageSize <= 0 {
		pageSize = 10
	}
	offset := (page - 1) * pageSize
	list, err := model.BargainProductList(offset, pageSize)
	if err != nil {
		return nil, err
	}

	var productList []*product.BargainProductListItem

	for _, item := range list {
		info, err := model.GetProductInfo(item.ProductId)
		if err != nil {
			return nil, err
		}
		productList = append(productList, &product.BargainProductListItem{
			Id:            item.Id,
			ProductId:     item.ProductId,
			StoreName:     info.StoreName,
			Image:         info.Image,
			Sales:         info.Sales,
			OriginalPrice: item.OriginalPrice,
			MinPrice:      item.MinPrice,
			TotalCuts:     item.TotalCuts,
			StartTime:     item.StartTime.Format("2006-01-02 15:04:05"),
			EndTime:       item.EndTime.Format("2006-01-02 15:04:05"),
		})
	}

	return &product.BargainProductListResponse{
		Total: int64(len(productList)),
		List:  productList,
	}, nil
}
